<?php

namespace backend\modules\business\controllers;

use common\models\BusEmployee;
use common\models\BusEmployeeReward;
use common\models\BusServiceExtend;
use common\models\BusServiceOrder;
use Yii;
use common\models\BusMember;
use common\models\BusService;
use common\models\BusConfig;
use common\models\BusMemberBeautycard;
use yii\data\Pagination;
use yii\helpers\Json;
use yii\helpers\Url;

// 服务
class ServerController extends \backend\controllers\BaseController
{
    /**
     * 会员拥有的卡列表
     * @param int $member_id 会员id
     * @param int $page 当前页
     */
    public function actionBeautycartd($member_id, $page = 1)
    {
        $list = BusMemberBeautycard::find()->where(['shop_id' => $this->userInfo->shop_id, 'member_id' => $member_id])->andWhere(['!=', 'remain_times', '0'])->asArray()->all();

        foreach ($list as $k => $val) {
            $list[$k]['avg_consume_amount'] = round($val['total_price'] / $val['total_times'], 2);
        }

        echo json_encode($list);
    }

    /**
     * 员工列表
     */
    public function actionEmployee()
    {
        $this->layout = '/alert';

        $pageSize = 4;

        $Employee = BusEmployee::find()->where(['shop_id' => $this->userInfo->shop_id, 'del_flag' => 1]);
        $pages = new Pagination(['totalCount' => $Employee->count(), 'pageSize' => $pageSize, 'defaultPageSize' => $pageSize]);
        $employeeList = $Employee->limit($pages->limit)->offset($pages->offset)->all();

        return $this->render('employee', [
            'employeeList' => $employeeList,
            'page' => $pages
        ]);
    }

    /**
     * 服务登记
     */
    public function actionRegister($key = '')
    {
        if (Yii::$app->request->isPost) {

            $BusService = new BusService();
            $Db = Yii::$app->db;

            $BusService->setAttributes($_POST);
            $BusService->shop_id = $this->userInfo->shop_id;
            $BusService->boss_id = $this->userInfo->boss_uid;
            $BusService->room_id = $BusService->room_id ?: 0;
            $BusService->room_name = $BusService->room_name ?: '';
            $BusService->make_time = $BusService->make_time ?: '0000-00-00 00:00:00';

            if (!$BusService->checkParams()) {
                $this->error($BusService->errorMessage);
            }

            if (!isset($_POST['beautycartd_id'])) {
                $this->error('请选择卡项');
            }
            if (!isset($_POST['employee_id'])) {
                $this->error('请选择员工');
            }
            /*if (!isset($_POST['room_id'])) {
                $this->error('请选择房间');
            }*/

            $serviceExtend = [];
            $card_id = [];
            $consume_count = 0;
            $employeeRewardData = [];
            $dateTime = date('Y-m-d H:i:s');

            if ($BusService->service_status == 2) {
                $BusService->service_endtime = $dateTime;
            }
            foreach ($_POST['beautycartd_id'] as $key => $beautycartd_id) {

                if (isset($_POST['reward']) && $_POST['reward'][$key]) {
                    if (!is_numeric($_POST['reward'][$key])) {
                        $this->error('员工提成必须是数字');
                    }
                    if ($_POST['reward'][$key] < 0) {
                        $this->error('员工提成不能低于0');
                    }
                }
                $BusService->service_addtime = $dateTime;
                if ($key == 0 && !$BusService->insert(false)) {
                    $this->error('登记服务失败');
                }

                $BusMemberBeautycard = BusMemberBeautycard::findOne($beautycartd_id);
                $BusEmployee = BusEmployee::findOne($_POST['employee_id'][$key]);

                $serviceExtend[] = [
                    $BusService->service_id, $beautycartd_id, $BusMemberBeautycard->card_name,
                    $_POST['employee_id'][$key], $BusEmployee->employee_name, $_POST['reward'][$key] ?: 0,
                    0, $_POST['avg_consume_amount'][$key] ?: '0', $BusService->service_member_id,
                    $this->userInfo->shop_id, $this->userInfo->boss_uid, $dateTime
                ];
                $Db->createCommand()->insert('bus_service_extend', [
                    'service_id' => $BusService->service_id,
                    'beautycartd_id' => $beautycartd_id,
                    'beautycartd_name' => $BusMemberBeautycard->card_name,
                    'employee_id' => $_POST['employee_id'][$key],
                    'employee_name' => $BusEmployee->employee_name,
                    'reward' => $_POST['reward'][$key] ?: 0,
                    'is_reward' => 0,
                    'consume_amount' => $_POST['avg_consume_amount'][$key] ?: '0',
                    'member_id' => $BusService->service_member_id,
                    'shop_id' => $this->userInfo->shop_id,
                    'boss_id' => $this->userInfo->boss_uid,
                    'add_time' => $dateTime
                ])->execute();

                if ($BusService->service_status == 2) {
                    $employeeRewardData[] = [
                        $_POST['employee_id'][$key], $_POST['reward'][$key] ?: 0, $dateTime,
                        $this->userInfo->shop_id, $this->userInfo->boss_uid, $_POST['avg_consume_amount'][$key] ?: '0',
                        $Db->lastInsertID
                    ];
                    $card_id[] = $beautycartd_id;
                    $consume_count += $_POST['avg_consume_amount'][$key] ?: 0;
                }
            }

            if ($BusService->service_status == 2) {
                // 计算累计服务次数
                $count = BusService::find()->where(['service_member_id' => $BusService->service_member_id, 'service_status' => 2])->count();
                $BusMember = BusMember::findOne($BusService->service_member_id);
                BusMember::updateAll([
                    'consume_counts' => $count,
                    'consume_count' => $consume_count + $BusMember->consume_count
                ], ['member_id' => $BusService->service_member_id]);

                $result = $Db->createCommand()->batchInsert('bus_employee_reward', [
                    'employee_id', 'handwork_reward', 'create_time',
                    'shop_id', 'boss_id', 'consume_reward',
                    'extend_id'
                ], $employeeRewardData)->execute();

                if ($result) {
                    BusServiceExtend::updateAll(['is_reward' => 1], ['service_id' => $BusService->service_id]);
                }

                // 减少疗程卡次数
                BusMemberBeautycard::updateAllCounters(['remain_times' => -1], ['card_id' => $card_id]);
                // 更新最后消费时间
                BusMember::updateAll(['last_consume_time' => date('Y-m-d H:i:s')], ['member_id' => $BusService->service_member_id]);
            }

            Yii::$app->session->setFlash('success', '提交成功！');
            return $this->redirect(['register']);
        }

        $pageSizeMember = 4;
        $Member = BusMember::find()->where(['shop_id' => $this->userInfo->shop_id, 'del_flag' => 1]);

        if ($key) { // 会员名、手机号码检索
            if (is_numeric($key)) {
                $Member->andWhere(['like', 'member_mobile', $key]);
            } else {
                $Member->andWhere(['like', 'member_name', $key]);
            }
        }

        $memberPages = new Pagination(['totalCount' => $Member->count(), 'pageSize' => $pageSizeMember, 'defaultPageSize' => $pageSizeMember]);
        $memberList = $Member->limit($memberPages->limit)->offset($memberPages->offset)->asArray()->all();

//        $roomList = BusConfig::find()->where(['shop_id' => $this->userInfo->shop_id, 'config_type' => 5])->limit(10)->asArray()->all();
        $roomList = BusConfig::find()
            ->select(['bus_config.*', 'bus_service.service_id'])
            ->leftJoin('bus_service', 'bus_service.room_id = bus_config.config_id AND bus_service.service_status = 1')
            ->where(['bus_config.shop_id' => $this->userInfo->shop_id, 'config_type' => 5])->asArray()->all();

        return $this->render('register', [
            'memberList' => $memberList,
            'memberPages' => $memberPages,
            'roomList' => $roomList
        ]);
    }

    /**
     * 正在服务
     */
    public function actionNow()
    {
        $pageSize = 9;
        $model = BusService::find()->where(['shop_id' => $this->userInfo->shop_id, 'service_status' => 1]);
        $pages = new Pagination(['totalCount' => $model->count(), 'pageSize' => $pageSize, 'defaultPageSize' => $pageSize]);

        $list = $model->with('members')->with('extends')->orderBy('service_addtime DESC')->asArray()->limit($pages->limit)->offset($pages->offset)->all();

        return $this->render('now', [
            'list' => $list,
            'page' => $pages
        ]);
    }

    /**
     * 修改服务状态
     * @param int $id 服务id
     * @param int $status 服务状态
     */
    public function actionChanges($id, $status)
    {
        if (Yii::$app->request->isAjax) {
            if (!is_numeric($id) || $id < 1 || !in_array($status, [0, 1, 2, 3])) {
                exit('0');
            }
            if (BusService::updateAll(['service_status' => $status], ['shop_id' => $this->userInfo->shop_id, 'service_id' => $id])) {
                if ($status == 2) { // 计算累计服务次数
                    $BusService = BusService::findOne($id);

                    $count = BusService::find()->where(['service_member_id' => $BusService->service_member_id, 'service_status' => 2])->count();

                    // 记录服务结束时间
                    BusService::updateAll(['service_endtime' => date('Y-m-d H:i:s')], ['service_id' => $id]);

                    // 记录员工调成

                    $extendList = BusServiceExtend::findAll(['service_id' => $id, 'is_reward' => 0]);
                    $employeeRewardData = [];
                    $card_id = [];
                    $consume_count = 0;
                    $dateTime = date('Y-m-d H:i:s');
                    foreach ($extendList as $val) {
                        $employeeRewardData[] = [
                            $val['employee_id'], $val['reward'], $dateTime,
                            $this->userInfo->shop_id, $this->userInfo->boss_uid, $val['consume_amount'],
                            $val['extend_id']
                        ];
                        $card_id[] = $val['beautycartd_id'];
                        $consume_count += $val['consume_amount'];
                    }
                    $result = Yii::$app->db->createCommand()->batchInsert('bus_employee_reward', [
                        'employee_id', 'handwork_reward', 'create_time',
                        'shop_id', 'boss_id', 'consume_reward',
                        'extend_id'
                    ], $employeeRewardData)->execute();

                    if ($result) {
                        BusServiceExtend::updateAll(['is_reward' => 1], ['service_id' => $id]);
                    }

                    $BusMember = BusMember::findOne($BusService->service_member_id);
                    BusMember::updateAll([
                        'consume_counts' => $count,
                        'consume_count' => $consume_count + $BusMember->consume_count,
                        'last_consume_time' => date('Y-m-d H:i:s')
                    ], ['member_id' => $BusService->service_member_id]);

                    // 减少疗程卡次数
                    BusMemberBeautycard::updateAllCounters(['remain_times' => -1], ['card_id' => $card_id]);
                } elseif ($status == 1) {
                    BusService::updateAll(['service_addtime' => date('Y-m-d H:i:s')], ['service_id' => $id]);
                }
                echo '1';
            } else {
                echo '0';
            }
        }
    }

    /**
     * 取消服务
     * @param int $id 服务id
     */
    public function actionCancel($id)
    {
        if (Yii::$app->request->isAjax) {
            if (!is_numeric($id) || $id < 1) {
                exit('0');
            }
            if (BusService::updateAll(['service_status' => 0], ['shop_id' => $this->userInfo->shop_id, 'service_id' => $id]) === false) {
                echo '0';
            } else {
                echo '1';
            }
        }
    }

    /**
     * 服务记录
     */
    public function actionRecord($member = '', $employee = '')
    {
        $field = [
            'bus_service.service_member_phone',
            'bus_service.service_member_name',
            'bus_service.service_addtime',
            'bus_service.service_endtime',
            'bus_service.service_id s_id',
            'bus_service.room_name',
            'bus_service.shop_id',
            'bus_service.make_time',

            'bus_service_extend.extend_id',
            'bus_service_extend.reward',
            'bus_service_extend.employee_name',
            'bus_service_extend.beautycartd_name',
            'bus_service_extend.employee_id',
            'bus_service_extend.reward',
        ];

        $model = BusService::find()->select($field)->where(['bus_service.shop_id' => $this->userInfo->shop_id, 'service_status' => 2])->innerJoin('bus_service_extend', 'bus_service.service_id = bus_service_extend.service_id');

        // 加入搜索的条件
        if (!empty($member)) {
            $model->andWhere(['like', 'service_member_name', $member]);
        }
        if (!empty($employee)) {
            $model->andWhere(['like', 'employee_name', $employee]);
        }

        $pages = new Pagination(['totalCount' => $model->count(), 'pageSize' => $this->pageNavLimit, 'defaultPageSize' => $this->pageNavLimit]);

        $list = $model->orderBy('service_addtime DESC')->asArray()->limit($pages->limit)->offset($pages->offset)->all();

        return $this->render('record',[
            'list' => $list,
            'page' => $pages
        ]);
    }

    /**
     * 预约记录
     */
    public function actionMake($type = 1)
    {
        if ($type == 1) { // 店铺预约
            $model = BusService::find()->where(['shop_id' => $this->userInfo->shop_id, 'service_status' => 3]);
            $pages = new Pagination(['totalCount' => $model->count(), 'pageSize' => $this->pageNavLimit, 'defaultPageSize' => $this->pageNavLimit]);

            $list = $model->with('extends')->asArray()->limit($pages->limit)->offset($pages->offset)->all();

            return $this->render('shopMake',[
                'list' => $list,
                'page' => $pages
            ]);
        } else { // app预约
            $model = BusServiceOrder::find()->where(['shop_id' => $this->userInfo->shop_id]);
            $pages = new Pagination(['totalCount' => $model->count(), 'pageSize' => $this->pageNavLimit, 'defaultPageSize' => $this->pageNavLimit]);
            $list = $model->asArray()->orderBy('order_time')->limit($pages->limit)->offset($pages->offset)->all();

            return $this->render('appMake', [
                'list' => $list,
                'page' => $pages
            ]);
        }

    }

    /**
     * 修改备注
     * @param int $id 服务记录id
     * @param string $u 跳转到本页面的某个方法
     * @return mixed
     */
    public function actionRemark($id = 0, $u = '', $member_id = null)
    {
        $this->layout = '/alert';
        if (!is_numeric($id) || $id < 1) {
            $this->error('参数错误');
        }
        if (($model = BusService::findOne(['shop_id' => $this->userInfo->shop_id, 'service_id' => $id])) === null) {
            $this->error('当前操作的记录不存在');
        }
        if ($model->load(Yii::$app->request->post())) {
            if (!$model->checkParams()) {
                $this->error($model->errorMessage);
            }
            $model->save(false);

            if ($member_id) {
                echo "<script>top.location.href='" . Url::to([$u, 'id' => $member_id]) . "'</script>";
            } else {
                echo "<script>top.location.href='" . Url::to([$u]) . "'</script>";
            }
        } else {
            return $this->render('remark', [
                'model' => $model
            ]);
        }
    }

    /**
     * 修改app预约的状态
     */
    public function actionEditserviceorder($order_id, $status = 1)
    {
        if (Yii::$app->getRequest()->isAjax && in_array($status, ['0', '1', '2'])) {
            if (BusServiceOrder::updateAll(['order_status' => $status], ['order_id' => $order_id])) {
                echo '1';
            } else {
                echo '0';
            }
        }
    }

    /**
     * 修改app预约状态为已到店状态的layer弹框
     */
    public function actionAppstate($order_id)
    {
        $this->layout = '/alert';
        if (!BusServiceOrder::findOne(['order_id' => $order_id, 'shop_id' => $this->userInfo->shop_id])) {
            $this->error('参数错误');
        }
        return $this->render('appstate');
    }

    /**
     * 确定跳转的页面
     */
    public function actionOrderredirect($order_id, $type)
    {
        BusServiceOrder::updateAll(['order_status' => 2], ['order_id' => $order_id]);
        if ($type) { // 收银
            echo "<script>top.location.href='" . Url::to(['/business/financial/cashier', 'order_id' => $order_id]) . "'</script>";
        } else { // 登记服务
            echo "<script>top.location.href='" . Url::to(['register', 'order_id' => $order_id]) . "'</script>";
        }
    }

    /**
     * 店铺预约点击开始服务的layer页面
     * @param int $s_id 服务记录id
     * @param int $m_id 服务的会员id
     * @return mixed
     */
    public function actionServicestart($s_id, $m_id)
    {
        $this->layout = '/alert';

        $request = Yii::$app->getRequest();
        if ($request->isPost) {
            if ($_POST['service_remark'] && \common\extended\system\Util::utf8_strlen($_POST['service_remark']) > 100) {
                $this->errorMessage = '备注不能超过100个字符';
                return false;
            }
            if (!isset($_POST['beautycartd_id'])) {
                $this->error('请选择卡项');
            }
            if (!isset($_POST['employee_id'])) {
                $this->error('请选择员工');
            }
            if (!isset($_POST['room_id'])) {
                $this->error('请选择房间');
            }
            $dateTime = date('Y-m-d H:i:s');
            $serviceExtend = [];
            foreach ($_POST['beautycartd_id'] as $key => $beautycartd_id) {

                if ($_POST['reward'][$key]) {
                    if (!is_numeric($_POST['reward'][$key])) {
                        $this->error('员工提成必须是数字');
                    }
                    if ($_POST['reward'][$key] < 0) {
                        $this->error('员工提成不能低于0');
                    }
                }

                $BusMemberBeautycard = BusMemberBeautycard::findOne($beautycartd_id);
                $BusEmployee = BusEmployee::findOne($_POST['employee_id'][$key]);

                $serviceExtend[] = [
                    $s_id, $beautycartd_id, $BusMemberBeautycard->card_name,
                    $_POST['employee_id'][$key], $BusEmployee->employee_name, $_POST['reward'][$key] ?: 0,
                    0, $_POST['avg_consume_amount'][$key] ?: '0', $m_id,
                    $this->userInfo->shop_id, $this->userInfo->boss_uid, $dateTime
                ];
            }
            BusServiceExtend::deleteAll(['service_id' => $s_id]);
            Yii::$app->db->createCommand()->batchInsert('bus_service_extend', [
                'service_id', 'beautycartd_id', 'beautycartd_name',
                'employee_id', 'employee_name', 'reward',
                'is_reward', 'consume_amount', 'member_id',
                'shop_id', 'boss_id', 'add_time'
            ], $serviceExtend)->execute();

            // 更新最后消费时间
//            BusMember::updateAll(['last_consume_time' => date('Y-m-d H:i:s')], ['member_id' => $m_id]);
            BusService::updateAll([
                'service_addtime' => $dateTime,
                'service_remark' => $request->post('service_remark', ''),
                'service_status' => 1,
                'room_id' => $_POST['room_id'],
                'room_name' => $_POST['room_name']
            ], ['service_id' => $s_id]);

            exit( "<script>top.location.href='" . Url::to(['make']) . "'</script>" );
        }

        // 房间列表
        $roomList = BusConfig::find()
            ->select(['bus_config.*', 'bus_service.service_id'])
            ->leftJoin('bus_service', 'bus_service.room_id = bus_config.config_id AND bus_service.service_status = 1')
            ->where(['bus_config.shop_id' => $this->userInfo->shop_id, 'config_type' => 5])->asArray()->all();

        // 会员的卡项列表
        $listBeautycard = BusMemberBeautycard::find()->where(['shop_id' => $this->userInfo->shop_id, 'member_id' => $m_id])->andWhere(['!=', 'remain_times', '0'])->asArray()->all();
        foreach ($listBeautycard as $k => $val) {
            $listBeautycard[$k]['avg_consume_amount'] = round($val['total_price'] / $val['total_times'], 2);
        }

        return $this->render('start', [
            'roomList' => $roomList,
            'listBeautycard' => $listBeautycard
        ]);
    }

    /**
     * 修改员工的手工提成
     * @param int $extend_id 服务记录扩展表的id
     * @param float $reward 手工提成
     */
    public function actionChangereward()
    {
//        header('Content-Type:application/json;charset=utf-8');
        header('Content-Type:application/json; charset=utf-8');
        $request = Yii::$app->getRequest();
        $extend_id = $request->post('extend_id');
        $reward = $request->post('reward');
        $employee_id = $request->post('employee_id');

        if (!is_numeric($reward) || $reward < 0) {
            exit( json_encode(['status' => 2, 'message' => '手工提成输入错误']) );
        }

        $re = Yii::$app->db->createCommand()->update('bus_employee_reward', ['handwork_reward' => $reward], [
            'extend_id' => $extend_id,
            'employee_id' => $employee_id,
            'shop_id' => $this->userInfo->shop_id
        ])->execute();
        if (is_numeric($re) && $re > 0) {
            // 修改扩展表的员工提成
            Yii::$app->db->createCommand()->update('bus_service_extend', ['reward' => $reward], [
                'extend_id' => $extend_id,
            ])->execute();
            echo json_encode(['status' => 1, 'message' => '修改成功']);
        } else {
            echo json_encode(['status' => 0, 'message' => '修改失败']);
        }

    }
}
